import math
import wave
import algebra

class Gerador:
	
	def __init__(self,wav,l):
		self.cord = None
		self.wavOriginal = wave.open(wav)
		self.l = l
		
	#def __init__(self,wav,l,x,y):
	#	self.cord = algebra.Ponto(x,y)
	#	self.wavOriginal = wave.open(wav)
	#	self.l = l
		
	def setCord(self,x,y):
		self.cord = algebra.Ponto(x,y)
		
	def getCord(self):
		return self.cord
		
	def calculaAtrasos(self):
		#Vm = /\S / /\t
		#/\t = /\S / Vm
		Vs = 340.29	* 100	# cm/s
		pontos = [algebra.Ponto(self.l,0),
					algebra.Ponto(0.5*self.l,math.sqrt(3)/2*self.l),
			 		algebra.Ponto(0,0)]
		#for ponto in pontos:
			#print ponto.x,ponto.y
		self.atrasos = []
		rate = self.wavOriginal.getframerate()
		self.deltas = []
		for i in range(3):
			deltaS = pontos[i].distanciaDe(self.cord)
			print 'distancia de (%s,%s) a (%s,%s) = %s' % (pontos[i].x,pontos[i].y,self.cord.x,self.cord.y,deltaS)
			t = deltaS / Vs
			#self.atrasos.append(int(round(t * rate)))
			self.atrasos.append(int(round(t * rate)))
			self.deltas.append(deltaS)	
	
	def atrasaWave(self,nomeSaida,atraso):
		wf = wave.open(nomeSaida, 'wb')
		wf.setnchannels(self.wavOriginal.getnchannels())
		wf.setsampwidth(self.wavOriginal.getsampwidth())
		wf.setframerate(self.wavOriginal.getframerate())
		print wf.getframerate()
		wf.setcomptype("NONE", "Uncompressed")
		listaAmostras = []
		tamanhoHexa = wf.getsampwidth()*wf.getnchannels()
		strConc = ''
		for i in range(tamanhoHexa):
			strConc = strConc + ' ' 
		stringAmostras = ''
		for i in range(atraso):
			stringAmostras = stringAmostras + strConc
		self.wavOriginal.rewind()
		temp = stringAmostras+self.wavOriginal.readframes(self.wavOriginal.getnframes())
		wf.writeframes(temp)
		wf.close()
		
	def geraWaves(self):
		for i in range(3):
			self.atrasaWave(('./audio/rec%s.wav' % (i+1)),self.atrasos[i])
		print self.atrasos
		
#########################################################
###########               TESTER              ###########

if __name__ == '__main__':
	ger = Gerador('./audio/teste.wav',30)
	ger.setCord(100,100)
	ger.calculaAtrasos()
	ger.geraWaves()
	print ger.atrasos
